// index.js
// 获取应用实例
const app = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Component({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },
  
  lifetimes: {
    attached() {
      // 检查是否已登录
      const userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.setData({
          userInfo,
          hasUserInfo: true
        })
      }
    }
  },
  
  methods: {
    // 选择头像
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail
      const { nickName } = this.data.userInfo
      this.setData({
        "userInfo.avatarUrl": avatarUrl,
        hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      })
      
      // 保存用户信息
      if (this.data.hasUserInfo) {
        wx.setStorageSync('userInfo', this.data.userInfo)
        app.globalData.userInfo = this.data.userInfo
      }
    },
    
    // 输入昵称
    onInputChange(e) {
      const nickName = e.detail.value
      const { avatarUrl } = this.data.userInfo
      this.setData({
        "userInfo.nickName": nickName,
        hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      })
      
      // 保存用户信息
      if (this.data.hasUserInfo) {
        wx.setStorageSync('userInfo', this.data.userInfo)
        app.globalData.userInfo = this.data.userInfo
      }
    },
    
    // 获取用户信息
    getUserProfile() {
      wx.getUserProfile({
        desc: '用于完善会员资料',
        success: (res) => {
          console.log(res)
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          // 保存用户信息
          wx.setStorageSync('userInfo', res.userInfo)
          app.globalData.userInfo = res.userInfo
        }
      })
    },
    
    // 跳转到绑定标签页面
    goToBindTag() {
      // 检查是否已登录
      if (!this.data.hasUserInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      wx.navigateTo({
        url: '/pages/bind-tag/bind-tag'
      })
    },
    
    // 跳转到我的标签页面
    goToMyTags() {
      // 检查是否已登录
      if (!this.data.hasUserInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      wx.navigateTo({
        url: '/pages/my-tags/my-tags'
      })
    }
  },
})
